package com.ai.dmc.utils.export;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownUtil {
	
	/**
	 * 下载文件
	 */
	public  void downFile(HttpServletRequest request, HttpServletResponse response){
		String path = request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\", "/").replaceAll("//", "/")+"file/";
		String fileName = request.getParameter("fileName");
	    response.setContentType("application/x-download");
        response.setContentType("application/OCTET-STREAM;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		
		File file = new File(path + File.separator + fileName);// 要下载的文件
		// 客户端下载
         try {
			downFile2Client(file,response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 下载文件到客户端
	 */
	public void downFile2Client(File file,HttpServletResponse response) throws Exception {
		OutputStream buffOut = null;
		FileInputStream buffIn = null;
		try {
			buffOut = response.getOutputStream();
			
			buffIn = new FileInputStream(file);
			int bytesRead = 0;// 当前现在字节数
			byte[] buff = new byte[10240];// 缓存
			while ((bytesRead = buffIn.read(buff, 0, 10240)) != -1) {
				buffOut.write(buff, 0, bytesRead);
			}
			// 首先清除记录下载录音记录的状态信息
			// request.getSession().removeAttribute("userDownInfo");
			buffOut.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
			// 清除临时文件
			if (buffOut != null) {
				try {
					buffOut.close();
				} catch (IOException e) {
					buffOut = null;
				}
				buffOut = null;
			}
			if (buffIn != null) {
				try {
					buffIn.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				buffIn = null;
			}
		}
	}
	
}
